//
//  GRUltimateHomeViewController.m
//  YC_GRice
//
//  Created by Feng Liu on 2018/9/22.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRUltimateHomeViewController.h"
#import "GRMyInfomationViewController.h"
#import "GRMyGRiceViewController.h"
#import "GRScanViewController.h"
#import <MAMapKit/MAMapKit.h>

#import "GRPersonModel.h"
#import "GRUltimateModel.h"
#import "GRUltimateTopBar.h"
#import "GRHoMeCollectionView.h"
#import "GRHoMeAnnotationView.h"
#import "GRUltimateAnnotation.h"
#import "GRSiftSortHUD.h"

static NSInteger bottomconstant = 59;
@interface GRUltimateHomeViewController () <MAMapViewDelegate, GRBasisProtocol, GRSiftSortHUDDelegate>
{
    BOOL isLoadingRequest;
    AMapPOI *poi;
    NSInteger category_id;
    BOOL isFreshLoc;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomLayout;

@property (weak, nonatomic) IBOutlet UIImageView *userAvatar;
@property (weak, nonatomic) IBOutlet UILabel *griceBalance;
@property (weak, nonatomic) IBOutlet UILabel *griceText;
@property (weak, nonatomic) IBOutlet UIButton *refreshBtn;
@property (nonatomic, strong) UIImageView *pinIMG;

@property (weak, nonatomic) IBOutlet GRUltimateTopBar *topBar;
@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (nonatomic, strong) GRHoMeCollectionView *collectionView;
@property (nonatomic, strong) GRUltimateModel *ultimateModel;
@property (nonatomic, strong) GRSiftSortHUD *sortHUD;

@property (nonatomic, strong) NSMutableDictionary *indexDictionary;

@end

@implementation GRUltimateHomeViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getRiceBalance];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self adjustDraw];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinishLocation:) name:GRDidFinishLocationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationFailure) name:GRDidLocationFailureNotification object:nil];
}

/**
 布局调整等*/
- (void)adjustDraw {
    if (IS_IPHONEX) {
        _topLayout.constant = 44;
        bottomconstant       = 59 + 34;
    }
    self.bottomLayout.constant = 40 + KscreenWidth/3 + bottomconstant + 10;
    
    self.topBar.delegate = self;
    
    self.mapView.delegate          = self;
    self.mapView.showsScale      = NO;
    self.mapView.showsCompass  = NO;
    self.mapView.zoomLevel        = 16;
    self.mapView.showsBuildings  = NO;
    self.mapView.rotateEnabled   = NO;
    self.mapView.runLoopMode    = NSDefaultRunLoopMode;
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode  = MAUserTrackingModeNone;
    
    self.pinIMG         = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Home_11"]];
    self.pinIMG.frame = CGRectMake(KscreenWidth/2-10.5, (KscreenHeight- self.bottomLayout.constant-10)/2-16.5, 21, 33);
    [self.view addSubview:self.pinIMG];
    
    CGFloat y = 0.5 - (KscreenHeight/2 - self.pinIMG.y - self.pinIMG.height) / KscreenHeight;
    self.mapView.screenAnchor  = CGPointMake(0.5, y);
    CGFloat collectionView_y     = self.topLayout.constant + 52;
    self.collectionView = [[GRHoMeCollectionView alloc] initWithFrame:CGRectMake(10, collectionView_y, KscreenWidth-20, KscreenHeight-collectionView_y - bottomconstant)];
    self.collectionView.currentVc = self;
    [self.view addSubview:self.collectionView];
    self.collectionView.hidden = YES;
}

/**
 定位完成通知
 */
- (void)didFinishLocation:(NSNotification *)notification {
    if ([notification.userInfo[FreshLoc] boolValue]) {
        isFreshLoc = YES;
    }
    [self LocationWithPOI:notification.userInfo[LocationKey] isDragMap:[notification.userInfo[DragMapKey] boolValue]];
}

- (void)locationFailure {
    [GRHUD showMessage:@"网络不给力" atView:self.view];
    self.refreshBtn.hidden     = NO;
    self.collectionView.hidden = YES;
}

- (void)LocationWithPOI:(AMapPOI *)aMpoi isDragMap:(BOOL)drapMap{
    poi = aMpoi;
    self.mapView.centerCoordinate = CLLocationCoordinate2DMake(aMpoi.location.latitude, aMpoi.location.longitude);
    if (!drapMap) {
        self.topBar.selectedCity.text   = poi.name;
        [self getNearbyShop];
    }else {
        [self loadNearbyShops];
    }
}

/**
 获取当前用户位置周围龟米店铺
 */
- (void)getNearbyShop {
    NSDictionary *paramer;
    if (isFreshLoc) {
        paramer = [self deployParamers:YES];
        isFreshLoc = NO;
    }else{
          paramer = [self deployParamers:NO];
    }
    WEAKSELF
    [GRHoMeAction getLocationShops:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
        [weakSelf unifyHandleResult:responseObject success:success error:error isDragMap:NO];
    }];
}


/**
 拖动地图，获取标点周围店铺
 */
- (void)loadNearbyShops {
    if (poi) {
        NSDictionary *paramer = [self deployParamers:YES];
        WEAKSELF
        [GRHoMeAction getNearbyStore:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
            [weakSelf unifyHandleResult:responseObject success:success error:error isDragMap:YES];
            isLoadingRequest = NO;
        }];
    }
}

- (NSDictionary *)deployParamers:(BOOL)dragMap {
    GRLocationManager *locationManager = [GRLocationManager defaultManager];
    NSDictionary *paramer = [@{@"areaCode"  : poi.adcode,
                              @"lantitude"   : @(poi.location.latitude),
                              @"longitude"   : @(poi.location.longitude),
                              @"loc"           : @[@(locationManager.currentLocation.longitude), @(locationManager.currentLocation.latitude)],
                              } mutableCopy];
    if (dragMap) {
        [paramer setValue:@(category_id) forKey:@"categoryId"];
    }
    return paramer;
}


/**
 统一处理结果 */
- (void)unifyHandleResult:(id)responseObject success:(BOOL)success error:(GRError *)error isDragMap:(BOOL)isDrag {
    if (success) {
        self.refreshBtn.hidden  = YES;
        if (isDrag) {
            [self addMapAnnotations:responseObject recycling:isDrag];
        }else {
            self.ultimateModel       = responseObject;
            self.sortHUD.classList = self.ultimateModel.classList;
            [self addMapAnnotations:self.ultimateModel.storeList recycling:isDrag];
        }
    }else {
        [GRHUD showMessage:error.errorMsg atView:self.view];
        self.refreshBtn.hidden = error.normalNetworkConnection;
    }
}

/**
 添加大头针 */
- (void)addMapAnnotations:(NSArray *)shops recycling:(BOOL)recycling{
    if (shops.count > 0) {
        self.collectionView.hidden = NO;
        NSMutableArray *annotations  = [NSMutableArray array];
        NSArray *shopArray              = [shops reverseObjectEnumerator].allObjects;
        for (GRUltimateShopModel *model in shopArray) {
            @autoreleasepool {
                NSLog(@"店铺名：%@\n",model.nickname);
                GRUltimateAnnotation *annotation = [[GRUltimateAnnotation alloc] init];
                annotation.title                          = model.nickname;
                annotation.shopModel                  = model;
                annotation.coordinate                 = model.coordinate;
                NSString *key = [NSString stringWithFormat:@"%ld",model.id];
                if (![self.indexDictionary.allKeys containsObject:key]) {
                    [self.indexDictionary setValue:model forKey:key];
                    [annotations addObject:annotation];
                    if (recycling) {
                        [self.ultimateModel.storeList insertObject:model atIndex:0];
                    }
                }else {
                    if (recycling) {
                        GRUltimateShopModel *shopModel = self.indexDictionary[key];
                        [self.ultimateModel.storeList removeObject:shopModel];
                        [self.ultimateModel.storeList insertObject:shopModel atIndex:0];
                    }
                }
            }
        }
        [self.mapView addAnnotations:annotations];
        [self.collectionView reloadDataWithNearbyShops:self.ultimateModel];
    }else {
        self.collectionView.hidden = YES;
    }
}



/**
 展示龟米余额
 */
- (void)getRiceBalance {
    WEAKSELF
    if ([GRUserBasisInfo isLogin]) {
        [GRPersonAction getMemberShipInfomation:^(BOOL success, id responseObject, GRError *error) {
            if (success) {
                weakSelf.RiceBalBox.hidden = NO;
                GRPersonModel *personModel = [GRPersonModel yy_modelWithDictionary:responseObject];
                [weakSelf.userAvatar sd_setImageWithURL:[NSURL URLWithString:personModel.avatar]];
                CGFloat fontSize   = KscreenWidth == 320 ? 14 : 15;
                weakSelf.griceText.font = [UIFont boldSystemFontOfSize:fontSize];
                NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%.2f",personModel.viewPoint]];
                [att addAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:fontSize]} range:NSMakeRange(0, 1)];
                weakSelf.griceBalance.attributedText = att;
            }
        }];
    }else {
        weakSelf.RiceBalBox.hidden = YES;
    }
}


/**
 断网情况下的刷新  */
- (IBAction)refreshWithNetworkDisconnect:(id)sender {
    WEAKSELF
    [self repositionAction:^{
        [weakSelf locatePinAnimation];
        [[GRLocationManager defaultManager] poiAroundSearch:weakSelf.mapView.centerCoordinate];
    }];
}

// 个人资料
- (IBAction)checkUserProfile:(id)sender {
    GRMyInfomationViewController *infoVc = [[GRMyInfomationViewController alloc] initWithStyle:UITableViewStylePlain];
    [self.navigationController pushViewController:infoVc animated:YES];
}

// 龟米余额
- (IBAction)checkMyRiceBalance:(id)sender {
    GRMyGRiceViewController *griceVc = [[GRMyGRiceViewController alloc] initWithStyle:UITableViewStylePlain];
    [self.navigationController pushViewController:griceVc animated:YES];
}


/**
 定位到当前位置
 */
- (IBAction)LocateToCurrentPosition:(id)sender {
   isFreshLoc = YES;
    
    WEAKSELF
    [self repositionAction:^{
        [weakSelf locatePinAnimation];
        [[GRLocationManager defaultManager] startUpdatingLocation];
    }];
}

- (IBAction)scanAction:(id)sender {
    if ([GRUserBasisInfo isLogin]) {
        GRScanViewController * scanVC = [[GRScanViewController alloc]init];
        [self.navigationController pushViewController:scanVC animated:YES];
        
    }else{
        [self goToLogin];
    }
    
}



- (void)repositionAction:(void(^)(void))completionHandler {
    if (!self.ultimateModel) {
        [[GRLocationManager defaultManager] startUpdatingLocation];
    }else {
        completionHandler();
    }
}

/**
 筛选分类
 */
- (IBAction)siftingSortAction:(id)sender {
    WEAKSELF
    [self repositionAction:^{
        [weakSelf.sortHUD showHUD];
    }];
}


#pragma MARK --------------   MAMapViewDelegate   ----------------
-(void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction {
    if (wasUserAction && !isLoadingRequest) {
        isLoadingRequest = YES;
        [self locatePinAnimation];
        [[GRLocationManager defaultManager] poiAroundSearch:mapView.centerCoordinate];
    }
}

- (void)mapView:(MAMapView *)mapView didAnnotationViewTapped:(MAAnnotationView *)view {
    if ([view.annotation isKindOfClass:[GRUltimateAnnotation class]]) {
        NSInteger index = [self.ultimateModel.storeList indexOfObject:[(GRUltimateAnnotation *)view.annotation shopModel]];
        [self.collectionView exchnageItemToFirstWithIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    }
}

static NSString *annotationReuseId = @"CustomAnnotationID";
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[GRUltimateAnnotation class]]) {
        GRHoMeAnnotationView *annotationView = (GRHoMeAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationReuseId];
        if (!annotationView) {
            annotationView = [[GRHoMeAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationReuseId];
        }
        NSString *key = ((GRUltimateAnnotation *)annotation).shopModel.categoryName;
        [annotationView.pinImageView sd_setImageWithURL:[NSURL URLWithString:self.ultimateModel.imgDictionary[key]]];
        annotationView.shopName = annotation.title;
        return annotationView;
    }
    return nil;
}

- (void)locatePinAnimation {
    WEAKSELF
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         CGPoint center = weakSelf.pinIMG.center;
                         center.y -= 20;
                         [weakSelf.pinIMG setCenter:center];}
                     completion:nil];
    
    [UIView animateWithDuration:0.45
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         CGPoint center = weakSelf.pinIMG.center;
                         center.y += 20;
                         [weakSelf.pinIMG setCenter:center];}
                     completion:nil];
}

#pragma Mark ----------- push到next控制器
-(void)didSelectedToNextViewController:(UIViewController *)viewController {
    [self.navigationController pushViewController:viewController animated:YES];
}

-(void)didRefreshNearbyShopWithClass:(NSInteger)categoryId {
    [self.indexDictionary removeAllObjects];
    [self.mapView removeAnnotations:self.mapView.annotations];
    category_id = categoryId;
    [self loadNearbyShops];
}

#pragma Mark ----------- 懒加载 ------------
-(GRSiftSortHUD *)sortHUD {
    if (!_sortHUD) {
        _sortHUD = [[GRSiftSortHUD alloc] init];
        _sortHUD.delegate = self;
    }
    return _sortHUD;
}

-(NSMutableDictionary *)indexDictionary {
    if (!_indexDictionary) {
        _indexDictionary = [NSMutableDictionary dictionary];
    }
    return _indexDictionary;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
